package 力扣._2359找到离给定两个节点最近的节点;

class Solution {
    public int closestMeetingNode(int[] edges, int node1, int node2) {
        int n = edges.length;
        // 保存节点1，2已经到达的节点
        int[] set1 = new int[n];
        int[] set2 = new int[n];
        int next1 = node1;
        int next2 = node2;
        boolean isOver1 = false;
        boolean isOver2 = false;

        set1[next1] = 1;
        set2[next2] = 1;

        while(!isOver1 && !isOver2){
            int t1 = Integer.MAX_VALUE;    // 节点1找到的节点
            int t2 = Integer.MAX_VALUE;    // 节点2找到的节点
            if(set2[next1]==1)
                t1 = next1;
            if(set1[next2]==1)
                t2 = next2;
            if(t1!=Integer.MAX_VALUE || t2!= Integer.MAX_VALUE){
                return Math.min(t1,t2);
            }
            // 节点1，2同步前进一步
            next1 = edges[next1];
            next2 = edges[next2];

            // 有环/ 走到头了
            if(next1==-1||set1[next1]==1)
                isOver1=true;
            if(next2==-1||set2[next2]==1)
                isOver2=true;

            if(!isOver1)
                set1[next1] = 1;
            if(!isOver2)
                set2[next2] = 1;
        }
        while (!isOver1){
            if(set2[next1]==1)
                return next1;
            next1 = edges[next1];
            if(next1==-1||set1[next1]==1)
                isOver1=true;
            if(!isOver1)
                set1[next1] = 1;
        }
        while (!isOver2){
            if(set1[next2]==1)
                return next2;
            next2 = edges[next2];
            if(next2==-1||set2[next2]==1)
                isOver2=true;
            if(!isOver2)
                set2[next2] = 1;
        }
        return -1;
    }
}